const { Product, User } = require('../models');
const logger = require('../utils/logger');

class OrderValidationService {
  /**
   * 验证订单创建数据
   * @param {object} orderData 订单数据
   * @param {object} user 用户对象
   * @returns {Promise<object>} 验证结果
   */
  static async validateOrderCreation(orderData, user) {
    const errors = [];
    const warnings = [];
    
    try {
      // 基础数据验证
      const basicValidation = this.validateBasicOrderData(orderData);
      if (!basicValidation.isValid) {
        errors.push(...basicValidation.errors);
      }
      
      if (errors.length > 0) {
        return {
          isValid: false,
          errors,
          warnings
        };
      }
      
      // 商品验证
      const itemsValidation = await this.validateOrderItems(orderData.items);
      if (!itemsValidation.isValid) {
        errors.push(...itemsValidation.errors);
      }
      warnings.push(...itemsValidation.warnings);
      
      // 用户验证
      const userValidation = await this.validateUser(user, orderData);
      if (!userValidation.isValid) {
        errors.push(...userValidation.errors);
      }
      warnings.push(...userValidation.warnings);
      
      // 积分验证
      const pointsValidation = this.validatePointsUsage(orderData, user);
      if (!pointsValidation.isValid) {
        errors.push(...pointsValidation.errors);
      }
      
      // 配送信息验证
      const deliveryValidation = this.validateDeliveryInfo(orderData.deliveryInfo);
      if (!deliveryValidation.isValid) {
        errors.push(...deliveryValidation.errors);
      }
      
      return {
        isValid: errors.length === 0,
        errors,
        warnings,
        validatedData: itemsValidation.validatedItems
      };
    } catch (error) {
      logger.error('订单验证失败:', error);
      return {
        isValid: false,
        errors: ['订单验证过程中发生错误'],
        warnings: []
      };
    }
  }

  /**
   * 验证基础订单数据
   * @param {object} orderData 订单数据
   * @returns {object} 验证结果
   */
  static validateBasicOrderData(orderData) {
    const errors = [];
    
    // 验证商品列表
    if (!orderData.items || !Array.isArray(orderData.items) || orderData.items.length === 0) {
      errors.push('订单商品不能为空');
    }
    
    // 验证支付方式
    const validPaymentMethods = ['points', 'wechat', 'alipay', 'cash'];
    if (orderData.paymentMethod && !validPaymentMethods.includes(orderData.paymentMethod)) {
      errors.push('无效的支付方式');
    }
    
    // 验证积分使用
    if (orderData.pointsUsed && (typeof orderData.pointsUsed !== 'number' || orderData.pointsUsed < 0)) {
      errors.push('使用积分必须为非负数');
    }
    
    // 验证备注长度
    if (orderData.notes && orderData.notes.length > 500) {
      errors.push('备注内容不能超过500字符');
    }
    
    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 验证订单商品
   * @param {Array} items 商品列表
   * @returns {Promise<object>} 验证结果
   */
  static async validateOrderItems(items) {
    const errors = [];
    const warnings = [];
    const validatedItems = [];
    
    if (!Array.isArray(items) || items.length === 0) {
      errors.push('商品列表不能为空');
      return { isValid: false, errors, warnings, validatedItems };
    }
    
    // 验证商品数量限制
    if (items.length > 50) {
      errors.push('单个订单最多只能包含50种商品');
    }
    
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      const itemErrors = [];
      
      // 验证商品ID
      const productId = parseInt(item.productId);
      if (isNaN(productId) || productId <= 0) {
        itemErrors.push(`商品${i + 1}: 无效的商品ID`);
        continue;
      }
      
      // 验证数量
      const quantity = parseInt(item.quantity);
      if (isNaN(quantity) || quantity <= 0) {
        itemErrors.push(`商品${i + 1}: 数量必须大于0`);
      } else if (quantity > 1000) {
        itemErrors.push(`商品${i + 1}: 单个商品数量不能超过1000`);
      }
      
      if (itemErrors.length > 0) {
        errors.push(...itemErrors);
        continue;
      }
      
      // 获取商品信息
      try {
        let product = await Product.findByPk(productId);
        
        // 如果数据库中没有找到商品，尝试使用模拟数据
        if (!product) {
          product = this.getMockProductById(productId);
          if (!product) {
            errors.push(`商品${i + 1}: 商品不存在`);
            continue;
          }
        }
        
        // 验证商品状态
        if (product.status !== 1) {
          errors.push(`商品${i + 1}: 商品已下架 - ${product.name}`);
          continue;
        }
        
        // 验证库存
        if (product.stock !== null) {
          if (product.stock < quantity) {
            errors.push(`商品${i + 1}: 库存不足 - ${product.name} (库存: ${product.stock}, 需要: ${quantity})`);
            continue;
          } else if (product.stock < quantity * 2) {
            warnings.push(`商品${i + 1}: 库存较少 - ${product.name} (剩余: ${product.stock})`);
          }
        }
        
        // 验证积分价格
        if (!product.points_price || product.points_price <= 0) {
          errors.push(`商品${i + 1}: 商品积分价格无效 - ${product.name}`);
          continue;
        }
        
        // 验证规格
        const specifications = item.specifications || {};
        if (product.specifications && Object.keys(product.specifications).length > 0) {
          const requiredSpecs = Object.keys(product.specifications);
          const providedSpecs = Object.keys(specifications);
          
          for (const requiredSpec of requiredSpecs) {
            if (!providedSpecs.includes(requiredSpec)) {
              warnings.push(`商品${i + 1}: 缺少规格 "${requiredSpec}" - ${product.name}`);
            }
          }
        }
        
        // 计算商品总积分
        const itemTotal = parseFloat(product.points_price) * quantity;
        
        validatedItems.push({
          productId: product.id,
          productName: product.name,
          quantity: quantity,
          unitPoints: parseFloat(product.points_price),
          totalPoints: itemTotal,
          specifications: specifications,
          product: product
        });
      } catch (error) {
        logger.error(`验证商品${productId}失败:`, error);
        errors.push(`商品${i + 1}: 验证商品信息失败`);
      }
    }
    
    return {
      isValid: errors.length === 0,
      errors,
      warnings,
      validatedItems
    };
  }

  /**
   * 验证用户信息
   * @param {object} user 用户对象
   * @param {object} orderData 订单数据
   * @returns {Promise<object>} 验证结果
   */
  static async validateUser(user, orderData) {
    const errors = [];
    const warnings = [];
    
    if (!user) {
      errors.push('用户信息不存在');
      return { isValid: false, errors, warnings };
    }
    
    // 验证用户状态
    if (user.status !== 1) {
      errors.push('用户账户已被禁用');
    }
    
    // 验证用户积分
    if (orderData.pointsUsed > 0 && user.points < orderData.pointsUsed) {
      errors.push(`积分不足 (当前: ${user.points}, 需要: ${orderData.pointsUsed})`);
    }
    
    // 检查用户今日订单数量限制
    try {
      const { Op } = require('sequelize');
      const { Order } = require('../models');
      
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const tomorrow = new Date(today);
      tomorrow.setDate(tomorrow.getDate() + 1);
      
      const todayOrderCount = await Order.count({
        where: {
          userId: user.id,
          createdAt: {
            [Op.gte]: today,
            [Op.lt]: tomorrow
          },
          status: {
            [Op.not]: 'cancelled'
          }
        }
      });
      
      const maxDailyOrders = 20; // 每日最大订单数
      if (todayOrderCount >= maxDailyOrders) {
        errors.push(`今日订单数量已达上限 (${maxDailyOrders}个)`);
      } else if (todayOrderCount >= maxDailyOrders * 0.8) {
        warnings.push(`今日订单数量较多 (${todayOrderCount}/${maxDailyOrders})`);
      }
    } catch (error) {
      logger.error('检查用户订单数量失败:', error);
      warnings.push('无法验证今日订单数量限制');
    }
    
    return {
      isValid: errors.length === 0,
      errors,
      warnings
    };
  }

  /**
   * 验证积分使用
   * @param {object} orderData 订单数据
   * @param {object} user 用户对象
   * @returns {object} 验证结果
   */
  static validatePointsUsage(orderData, user) {
    const errors = [];
    
    // 对于积分兑换系统，我们需要验证用户是否有足够积分
    // 这里不使用orderData.pointsUsed，而是计算实际需要的积分
    
    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 验证配送信息
   * @param {object} deliveryInfo 配送信息
   * @returns {object} 验证结果
   */
  static validateDeliveryInfo(deliveryInfo) {
    const errors = [];
    
    if (!deliveryInfo) {
      return { isValid: true, errors }; // 配送信息可选
    }
    
    // 验证配送方式
    const validDeliveryMethods = ['pickup', 'delivery'];
    if (deliveryInfo.deliveryMethod && !validDeliveryMethods.includes(deliveryInfo.deliveryMethod)) {
      errors.push('无效的配送方式');
    }
    
    // 如果是配送，验证配送信息
    if (deliveryInfo.deliveryMethod === 'delivery') {
      if (!deliveryInfo.recipientName || deliveryInfo.recipientName.trim().length === 0) {
        errors.push('收货人姓名不能为空');
      } else if (deliveryInfo.recipientName.length > 50) {
        errors.push('收货人姓名不能超过50字符');
      }
      
      if (!deliveryInfo.phone || !/^1[3-9]\d{9}$/.test(deliveryInfo.phone)) {
        errors.push('请输入有效的手机号码');
      }
      
      if (!deliveryInfo.address || deliveryInfo.address.trim().length === 0) {
        errors.push('收货地址不能为空');
      } else if (deliveryInfo.address.length > 200) {
        errors.push('收货地址不能超过200字符');
      }
    }
    
    // 验证配送费
    if (deliveryInfo.deliveryFee !== undefined) {
      const fee = parseFloat(deliveryInfo.deliveryFee);
      if (isNaN(fee) || fee < 0) {
        errors.push('配送费必须为非负数');
      } else if (fee > 50) {
        errors.push('配送费不能超过50元');
      }
    }
    
    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 计算订单金额
   * @param {Array} validatedItems 已验证的商品列表
   * @param {object} orderData 订单数据
   * @returns {object} 金额计算结果
   */
  static calculateOrderAmount(validatedItems, orderData) {
    // 计算商品总积分
    const totalPoints = validatedItems.reduce((sum, item) => sum + item.totalPoints, 0);
    
    // 对于积分兑换系统，我们使用积分作为主要货币
    // 这里保持与原有API兼容的字段名，但实际都是积分
    const pointsUsed = totalPoints;
    const pointsEarned = 0; // 积分兑换不额外获得积分
    
    return {
      totalAmount: totalPoints,      // 实际是总积分
      discountAmount: 0,             // 积分兑换没有折扣
      finalAmount: totalPoints,      // 实际是总积分
      pointsUsed: pointsUsed,        // 使用的积分
      pointsEarned: pointsEarned     // 获得的积分
    };
  }

  /**
   * 验证订单金额
   * @param {object} amounts 金额信息
   * @returns {object} 验证结果
   */
  static validateOrderAmount(amounts) {
    const errors = [];
    
    // 验证最小订单积分
    const minOrderPoints = 1;
    if (amounts.finalAmount < minOrderPoints) {
      errors.push(`订单积分不能少于${minOrderPoints}积分`);
    }
    
    // 验证最大订单积分
    const maxOrderPoints = 10000;
    if (amounts.totalAmount > maxOrderPoints) {
      errors.push(`订单积分不能超过${maxOrderPoints}积分`);
    }
    
    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 获取模拟商品数据（用于数据库不可用时）
   * @param {number} productId - 商品ID
   * @returns {Object|null} 模拟商品数据
   */
  static getMockProductById(productId) {
    const mockProducts = {
      1: {
        id: 1,
        name: '专业彩色打印服务',
        description: '高质量彩色打印，适用于各类文档、图片、海报等。使用进口墨水，色彩鲜艳持久。支持多种纸张类型，满足不同需求。',
        price: 15.00,
        original_price: 20.00,
        points_price: 100,
        is_points_product: true,
        cover_image: '/static/icons/default-product.svg',
        category: 'print',
        type: 'color_print',
        stock: 999,
        is_hot: true,
        is_new: false,
        status: 1,
        sort_order: 100,
        specifications: {
          paper_type: 'coated',
          paper_weight: '120',
          paper_size: 'A4',
          color_mode: 'color',
          sides: 'double',
          dpi: '1200',
          finish: 'glossy'
        }
      },
      2: {
        id: 2,
        name: '黑白文档打印',
        description: '经济实惠的黑白打印服务，适合日常文档、作业、报告等。清晰度高，成本低廉。',
        price: 8.00,
        original_price: 10.00,
        points_price: 50,
        is_points_product: true,
        cover_image: '/static/icons/default-product.svg',
        category: 'print',
        type: 'black_white_print',
        stock: 999,
        is_hot: false,
        is_new: false,
        status: 1,
        sort_order: 90,
        specifications: {
          paper_type: 'normal',
          paper_weight: '80',
          paper_size: 'A4',
          color_mode: 'black',
          sides: 'single',
          dpi: '600',
          finish: 'matte'
        }
      },
      3: {
        id: 3,
        name: '螺旋装订服务',
        description: '专业螺旋装订，可180度平摊，适合笔记本、日历、教材等装订。牢固耐用，美观实用。',
        price: 12.00,
        original_price: 15.00,
        points_price: 80,
        is_points_product: true,
        cover_image: '/static/icons/default-product.svg',
        category: 'binding',
        type: 'spiral_binding',
        stock: 500,
        is_hot: false,
        is_new: true,
        status: 1,
        sort_order: 80,
        specifications: {
          binding_type: 'spiral',
          max_pages: 120,
          cover_options: '透明封面+硬卡纸封底',
          colors: '黑色、白色、蓝色可选',
          material: '优质塑料螺旋圈'
        }
      }
    }

    return mockProducts[productId] || null
  }
}

module.exports = OrderValidationService;